package com.scalar.chiptrack.finance.proformainvoice.actioncommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;

import com.scalar.chiptrack.operations.release.ReleaseHelper;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.ErrorReport;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.finance.proformainvoice.forms.ProformaInvoiceForm;
import com.scalar.chiptrack.finance.proformainvoice.dao.ProformaInvoiceDAO;
import com.scalar.chiptrack.finance.proformainvoice.ProformaInvoiceHelper;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

/**
 * User: KP
 * Date: Sep 28, 2006
 * Time: 3:10:16 PM
 */
public class ProformaInvoiceModifyCommand extends ActionCommand
{
    private static final String ACTION_NAME = "/newproformaInvoice.do";

    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws ScalarException
    {
        try
        {
            request.setCharacterEncoding( "UTF-8" );
        } catch (UnsupportedEncodingException e) { }

        ProformaInvoiceForm invoiceForm = ( ProformaInvoiceForm ) form;
        ActionForward actionForward = mapping.findForward( "modify" );
        HttpSession mSession        = request.getSession();
        User user                   = ( User ) mSession.getAttribute ( SessionKeys.USER_KEY );
        HashMap errors              = new HashMap();
        HashMap info                = new HashMap();

        String action                   = request.getParameter("action");
        String refreshedByUser          = request.getParameter("refreshedByUser");

        request.setAttribute( INFO_MESSAGES, info );
        request.setAttribute( ERROR_MESSAGES, errors );

        if ( user == null )
        {
            mSession.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME);
            return ( mapping.findForward ( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.PRO_FORMA_INVOICE, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }

        request.setAttribute( "actionType", action );

        try
        {
            int invoiceId = -1;
            HashMap bankInfoMap = new HashMap();
            try
            {
                invoiceId = Integer.parseInt( ( ( String ) request.getParameter( "invoiceId" ) ) );
            }catch( NumberFormatException nfe ){ invoiceId = -1; }

            if( invoiceId > 0 )
            {
                int finalbankId = 0;
                String bankId = request.getParameter("bankId");

                if( bankId != null && bankId.trim().length() != 0 )
    	        {
			       finalbankId = Integer.parseInt(bankId);
	        	}
                ProformaInvoiceHelper.resetProformaInvoiceForm( invoiceForm );
                ProformaInvoiceDAO.loadCompleteProformaInvoiceDetails( invoiceForm, invoiceId );
                 finalbankId = UserDAO.loadBankId();
                bankInfoMap = UserDAO.loadClientBankAddressDetails( null , finalbankId );
			    request.setAttribute( "BankInfo" , bankInfoMap );
                request.setAttribute( "AllBankNames", UserDAO.getAllBankNames());
            }

            if( ACTION_VIEW.equalsIgnoreCase( action ) || ACTION_CANCEL.equalsIgnoreCase( action ) )
            {
                if( ACTION_CANCEL.equalsIgnoreCase( action ) )
                {
                    request.setAttribute( "isCancelled", "true" );// Used to show Confirm Button in view screen
                }
                actionForward = mapping.findForward( "view" );
            }
            else if( ACTION_PRINT_VIEW.equalsIgnoreCase( action ) )
            {
                actionForward = mapping.findForward( ACTION_PRINT_VIEW );
            }
            else if( ACTION_MODIFY.equalsIgnoreCase( action ) )
            {
                actionForward = mapping.findForward( "modify" );
            }
            else if( ACTION_APPROVE.equalsIgnoreCase( action ) )
            {
                actionForward = mapping.findForward( "approve" );
            }
        }
        catch ( Exception e )
        {
            Logger.error( "Error while processing the request for retreiving the Proforma Invoice details", e );
            errors.put( ERROR_INTERNAL_SERVER_ERROR, "Error while processing the request for retreiving the Proforma Invoice details" );

            mSession.setAttribute( ERROR_REPORT_OBJECT, new ErrorReport( "Error while processing the request for retreiving the Proforma Invoice details", e ) );

            request.setAttribute( "yearList", ReleaseHelper.getYearList() );
            request.setAttribute( "partNumberList", NewProductDAO.loadPartNumbers (null, 1, Constants.LOCATION_TYPE_FG, true, true, true, 0 ) );

            actionForward = mapping.findForward( "search_invoices" );
            e.printStackTrace();
        }

      
        saveToken( request );

        return actionForward;
    }

}
